/*
 * @(#)SageProcessor.java $version 2012. 1. 31.
 *
 */

package com.mywep.myalimi.batch.sage;

import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;

import com.mywep.myalimi.common.DbConditionHolder;
import com.mywep.myalimi.common.http.RssRepository;
import com.mywep.myalimi.constant.Constants;
import com.mywep.myalimi.constant.ContentType;
import com.mywep.myalimi.model.Engine;
import com.mywep.myalimi.model.Keyword;
import com.mywep.myalimi.model.KeywordAndContents;
import com.mywep.myalimi.model.NewContent;
import com.mywep.myalimi.model.Rss;
import com.mywep.myalimi.repository.engine.EngineRepository;

import com.nhncorp.lucy.spring.core.util.ExtendedMap;

/**
 * @author 한지웅
 */
public class SageProcessor implements ItemProcessor<List<Keyword>, KeywordAndContents> {

	@Autowired
	private EngineRepository engineRepository;
	@Autowired
	private RssRepository rssRepository;

	/**
	 * @param keywordList
	 * @return
	 * @throws Exception
	 * @see org.springframework.batch.item.ItemProcessor#process(java.lang.Object)
	 */
	@Override
	public KeywordAndContents process(List<Keyword> keywordList) throws Exception {
		ExtendedMap param = DbConditionHolder.getInstance();
		param.put("use_yn", Constants.YesNo.YES.toString());
		List<Engine> engineList = engineRepository.selectByExample(param);
		
		KeywordAndContents newContents = new KeywordAndContents();
		Calendar calendar = Calendar.getInstance();
		Date nowDate = calendar.getTime();
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		for (Engine engine : engineList) {
			for (Keyword keyword : keywordList) {
				String searchUrl = engine.getUrl() + "&query=" + URLEncoder.encode(keyword.getKeyword(), "EUC-KR");
				List<Rss> rssList = rssRepository.selectRSS(searchUrl);
				for(Rss rss : rssList){
					Date beforeDay = calendar.getTime();
					if (beforeDay.after(rss.getDate())) {
						continue;
					}
					NewContent newContent = new NewContent();
					newContent.setKeyword(keyword.getKeyword());
					newContent.setContextType(ContentType.getContentTypeByEngineType(engine.getEngineType()).toString());
					newContent.setRegDate(rss.getDate());
					newContent.setTitle(rss.getTitle());
					newContent.setUrl(rss.getUrl());
					newContent.setInsertDate(nowDate);
					newContent.setSummary(rss.getDescription());
					newContent.setAuth(rss.getAuth());
					newContents.getContents().add((newContent));

				}
				
				newContents.getKeywords().add(keyword.getKeyword());

			}
			
		}
		
		return newContents;
	}

}
